class User < ActiveRecord::Base


  PHONE_FORMAT = /\A1\d{10}\z/
  EMAIL_FORMAT = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i

  validates :password, presence: { on: :create, message: "您忘了输入密码了..." }, \
      confirmation: { message: "确认密码不匹配" }
  validates :password, length: { minimum: 6, maximum: 32, \
      too_short: "密码至少为%{count}个字符哦", \
      too_long: "密码太长啦, 最多为%{count}个字符哦" }, allow_blank: true   



  def password
    @password
  end

  def password=(password)
    @password = password
    return if password.blank?

    create_new_salt
    self.hashed_password = self.class.encrypted_password(self.password, self.hash_salt)
  end


  class << self

    def authenticate(login, password)
      if user = find_by_login(login)
        expected_password = encrypted_password(password, user.hash_salt)
        return user if expected_password == user.hashed_password
      end
    end

    def find_by_login(login)
      return login if login.is_a?(User)
      login_type = type_of_login(login)
      user = where(login_type => login).first
      if user.blank? && login_type != :email
        user = where(email: login).first
      end
      user
    end

    def type_of_login(login)
      login = login.to_s
      if login =~ PHONE_FORMAT
        :phone
      elsif login =~ EMAIL_FORMAT
        :email
      else
        :email
      end
    end

    def friendly_token(length = 15)
      SecureRandom.base64(length).tr('+/=lIO0', 'pqrsxyz')
    end

    def encrypted_password(password, salt)
      string_to_hash = (salt.blank? ? "#{password}" : "#{password}goddamn#{salt}") 
      Digest::MD5.hexdigest(string_to_hash)
    end
  end

  private


  def create_new_salt
    self.hash_salt = User.friendly_token
  end



end
